/*!
 * 图片上传模块
 * @author Sherlock 
 * ----------------------------
 * uploaded 上传完成 但未保存属性的函数
 * dosave 保存后的回调函数
 */
require( './style.less' );
define( [
  'require',
  'jquery',
  'message',
  'qiniu', // 依赖七牛上传组件
  'constants',
  'bootstrap',
  'bootstrap-select',
  'api',
  'imgCategory',
  'artTemplate'
], function( require, $, ShowTitleMessage ) {
  'use strict';

  var returnParam = {};

  var showTime = ShowTitleMessage.showTime;
  var constants = require( 'constants' );
  var apis = require( 'api' ).FILEUPLOAD;
  var imgCategory = require( 'imgCategory' );
  var at = require( 'artTemplate' );
  var callbackBackupFn = {};
  var callbackBackup = function() {};

  var me = returnParam.$selector = $( '#img-upload-modal' );
  var that = returnParam.$uploadFinish = $( '#img_upload_finished' );

  var categoryTemp = at.compile( '{{each list}}<option value="{{$index}}">{{$value}}</option>{{/each}}' )( {
    list: $.extend( {
      "": "未分类"
    }, imgCategory.pictureClassify )
  } );

  $( '.video_classify', me ).html( categoryTemp );
  $( '.img_classfy', that ).html( categoryTemp );

  $( '.selectpicker', that ).selectpicker( {
    size: 8
  } );

  // 从window下获取七牛SDK
  var option_image = {
    runtimes: 'html5,flash,html4', // 上传模式,依次退化
    browse_button: 'image_upload', // 上传选择的点选按钮，**必需**
    uptoken_url: apis.GET_IMG_UPTOKEN, // Ajax 请求 uptoken 的 Url，**强烈建议设置**（服务端提供）
    get_new_uptoken: false, // 设置上传文件的时候是否每次都重新获取新的 uptoken
    domain: constants.qiniuDomainImg, // bucket 域名，下载资源时用到，**必需**
    max_file_size: constants.imageMaxSize, // 最大文件体积限制
    flash_swf_url: 'path/of/plupload/Moxie.swf', //引入 flash,相对路径
    max_retries: 0, // 上传失败最大重试次数
    dragdrop: true, // 开启可拖曳上传
    chunk_size: constants.imageMaxSize, // 分块上传时，每块的体积
    auto_start: false, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传,
    multi_selection: false, // 是否多选
    filters: {
      mime_types: [ {
        title: 'Image files',
        extensions: 'jpg,jpeg,png,gif,bmp'
      } ]
    },
    init: {
      Key: function( up, file ) {
        var name = file.name;
        var ext = name.split( '.' );
        var key = constants.userLogin + '_' + ( new Date().getTime() ) + parseInt( Math.random() * 100 ) + '.' + ext[ 1 ];
        return key;
      }
    }
  };

  function init( id, callback, initCallback ) {
    initCallback = initCallback || {};
    if ( typeof callback === 'object' ) {
      initCallback = callback;
      callback = null;
    }
    if ( !initCallback.init ) initCallback.init = {};

    var successBackup = initCallback.init.FileUploaded;
    var errorBackup = initCallback.init.Error;

    initCallback.init.FileUploaded = function( up, file, info ) {
      // 代理
      info = $.parseJSON( info || '{}' );
      ShowTitleMessage.hide();


      // 执行回调
      typeof callback === 'function' && callback.apply( this, [ up, file, info ] );
      typeof successBackup === 'function' && successBackup.apply( this, [ up, file, info ] );
    };

    initCallback.init.Error = function( up, err, errTip ) {
      // 代理

      if ( err.code === -600 ) {
        ShowTitleMessage.showWarning( '文件大小超出' + constants.imageMaxSize, showTime );
      } else {
        ShowTitleMessage.showWarning( '上传出现问题，请联系管理员', showTime );
      }

      $( '#do_finish', that.modal( 'hide' ) ).removeAttr( 'disabled' );

      typeof errorBackup === 'function' && errorBackup.apply( this, arguments );
    }

    // 这里需要深拷贝
    $.extend( true /* 深拷贝 */ , $.extend( option_image, {
      browse_button: id
    } ), initCallback );

    return new QiniuJsSDK().uploader( option_image );
  }

  // 老的上传弹框
  init( 'image_upload', {
    init: {
      'FileUploaded': function( up, file, info ) {

        ShowTitleMessage.show( '图片上传成功', showTime );
        $( '.image_upload', me ).parent().find( '.add_icon1' ).attr( 'style', 'display:none' );
        $( '.image_upload', me ).text( '重新上传' );
        $( '#imageId', me ).val( info.image_id || '' );
        var content = '<div id="example_image_qiniu" class="add-show">' +
          '<a value="删除" class="delete">删除</a>' +
          '<img src="' + info.url + '"></div>';
        $( '.image_preview', me ).html( content );
        if ( $.isFunction( returnParam.uploaded ) ) {
          returnParam.uploaded.call( this, up, file, info );
        }

      },
      'Error': function( up, err, errTip ) {
        $( '.progress_bar .bar', me ).css( {
          'width': '0%'
        } );
        $( 'input[type="file"]', me ).val( '' );
      },
      'BeforeUpload': function( up, file ) {
        this.msgDom = ShowTitleMessage.show( '图片上传中' )[ 0 ];
      },
      'UploadProgress': function( up, file ) {
        this.msgDom && ( this.msgDom.innerText = '图片上传中 ' + file.percent + '%' );
      },
      'FilesAdded': function( up, files ) {
        up.start();
      }
    }
  } );

  // 初始化参数包括一些默认代理
  returnParam.init = function( id, callback, uploadDetail ) {
    var _this = this;

    var FilesAdded = uploadDetail && uploadDetail.init && uploadDetail.init.FilesAdded;

    callbackBackupFn[ id ] = callback;
    document.getElementById( id ).addEventListener( 'click', function() {
      callbackBackup = callbackBackupFn[ id ];
    }, false );

    return init.apply( this, [ id, function( up, file, info ) {

      $( '[name="image_id"]', that ).val( info.image_id );
      $( '.bg_container', that ).data( 'url', info.url );
      var formData = getImgUploadFinishedData();

      // 如果是自动上传就取出文件名再保存
      up.getOption().auto_start && ( formData.title = file.name );

      $( '#do_finish', that ).prop( 'disabled', 'disabled' );
      doSaveAjaxRequest( formData, function() {
        that.modal( 'hide' );
        ShowTitleMessage.hide();
        $( 'form', that )[ 0 ].reset();
        callbackBackup( formData );
      } ).always( function() {

        $( '#do_finish', that ).removeAttr( 'disabled' );

      } );
    }, $.extend( true, uploadDetail, {
      init: {
        FilesAdded: function( up, files ) {
          if ( !this.getOption().auto_start && !this.getOption().not_show_modal ) {
            var file = files[ 0 ];
            that.data( 'uploader', up );
            $( '[name="name"]', that ).val( file.name );
            imgPreivew( file.getNative(), $( '.bg_container', that.modal( 'show' ) ) );
          }

          $.isFunction( FilesAdded ) && FilesAdded.apply( this, arguments );
        }
      }
    } ) ] );
  };

  function imgPreivew( file, bgContainer ) {

    if ( typeof FileReader === 'undefined' ) bgContainer.html( "<p style='position: absolute;top: 40%;width:100%;text-align: center;'>浏览器版本较低，无法预览</p>" );
    else {
      bgContainer.empty();

      var reader = new FileReader();
      // 将文件读取为DataUrl  
      reader.readAsDataURL( file );

      reader.onload = function( event ) {
        bgContainer.css( {
          backgroundImage: 'url(' + this.result + ')'
        } );
      };

      reader.onerror = function( event ) {
        throw new Error( '读取出错' );
      };

    }
  }

  // 绑定事件
  that.on( 'click', '#do_finish', function() {
    var formData = getImgUploadFinishedData();
    if ( formData.title === '' ) {
      return ShowTitleMessage.showWarning( '请输入图片标题', showTime );
    }
    if ( formData.cc === '' ) {
      return ShowTitleMessage.showWarning( '请先选择分类', showTime );
    }
    var uploader = that.data( 'uploader' );
    uploader && uploader.start();

  } ).on( 'hide.bs.modal', function() {
    // 模态框隐藏时移除里面的上传队列
    var uploader = $( this ).data( 'uploader' );
    uploader && uploader.splice( 0, uploader.files.length );
  } );

  function submitCheck( checkData, fn, beforeSub ) {
    if ( checkData.title === '' ) {
      ShowTitleMessage.showWarning( '请输入图片标题', showTime );
      return false;
    }

    if ( checkData.cc === '' ) {
      ShowTitleMessage.showWarning( '请先选择分类', showTime );
      return false;
    }
    if ( !checkData.label ) {
      ShowTitleMessage.showWarning( '请输入标签', showTime );
      return false;
    }

    if ( !checkData.image_id ) {
      ShowTitleMessage.showWarning( '请先上传图片', showTime );
      return false;
    }

    ShowTitleMessage.show( '正在保存' );
    $.isFunction( beforeSub ) && beforeSub.call( this );
    return doSaveAjaxRequest.apply( this, [ checkData, fn ] );
  }

  function doSaveAjaxRequest( subData, fn ) {
    return $.ajax( {
      url: apis.SAVE_IMAGE,
      type: 'post',
      data: subData,
      async: false,
      success: function( data ) {
        var htm = $.parseJSON( data );
        $.isFunction( fn ) && fn.call( this, htm );
      }
    } );
  }

  function getImgUploadFinishedData() {
    var labels = $( '[name="label"]', that ).val().split( '\n' );
    var tempLabel = [];
    $.each( labels, function( k, v ) {
      if ( $.trim( v ) !== '' ) {
        if ( tempLabel.push( $.trim( v ) ) == 4 ) return false;
      }
    } );

    return {
      image_id: $( '[name="image_id"]', that ).val().trim(),
      id: $( '[name="image_id"]', that ).val().trim(),
      title: $( '[name="name"]', that ).val().trim(),
      classify: $( '[name="cc"] option:selected', that ).text(),
      cc: $( '[name="cc"]', that ).val(),
      // 标签4个限制
      label: tempLabel.join( ',' ),
      image: $( '.bg_container', that ).data( 'url' ),
      is_show: $( '[name="is_show"]', that ).is( ':checked' ) ? 1 : ''
    };
  }

  /*
   * 文本长度监听
   */
  $( '.img_name', me ).bind( 'input propertychange', function() {
    var area = $( this ).val().length;
    $( ".spa_fontcount > span", me ).text( area );
  } );

  // 点击保存按钮
  $( '#upload-img-btn', me ).click( function() {
    var is_show = 0;
    var image = $( '#example_image_qiniu img' ).prop( 'src' );
    var image_id = $( '#imageId', me ).val();
    var title = $.trim( $( '.img_name', me ).val() );
    var classify = $( 'select.video_classify', me ).val();
    var classifyName = $( 'select.video_classify option:selected', me ).text();
    var label = '';
    $( '.tag-choosed-img', me ).find( 'button' ).each( function() {
      label += $( this ).text() + ',';
    } );
    label = label.substring( 0, label.length - 1 );



    if ( $( '#image_share', me ).is( ':checked' ) ) {
      is_show = 1;
    }

    var paramData = {
      image_id: image_id,
      id: image_id,
      title: title,
      classify: classifyName,
      cc: classify,
      label: label,
      image: image,
      is_show: is_show
    };

    submitCheck( paramData, function( htm ) {
      if ( typeof htm.ret != 'undefined' && htm.ret != 0 ) {
        ShowTitleMessage.showWarning( "图片保存失败", showTime );
        return;
      }

      ShowTitleMessage.show( "图片保存成功", showTime );

      $( '#fm_img_upload', me.modal( 'hide' ) )[ 0 ].reset();
      if ( $.isFunction( returnParam.doSave ) ) {
        returnParam.doSave.call( this, htm, paramData );
      }
    } );
  } );

  // -----------------------------上传图片标签处理-------------------------
  function multipleParam( option ) {
    var param = {
      maxOptions: 5,
      selectedTextFormat: 'values',
      multipleSeparator: ',',
      noneSelectedText: '请选择',
      size: 8,
      //container: '#img-upload-modal'
    }
    if ( option ) {
      return $.extend( param, option );
    } else {
      return param;
    }
  }

  $( '.video_classify', me ).selectpicker( {
    size: 8
  } );

  $( '.select-tag', me ).selectpicker( multipleParam() ).on( 'change', function() {
    var valList = $( this ).val() + "";
    var array = valList.split( ',' );
    var html = '';
    if ( array != 'null' ) {
      for ( var i = 0; i < array.length; i++ ) {
        html += '<button type="button" title="' + array[ i ] + '">' + array[ i ] + '</button>';
      }
    }
    $( '.tag-choosed-img>.system-tag', me ).html( html );
  } );


  $( '.tag-choosed-img>.system-tag', me ).on( 'click', 'button', function() {
    $( this ).remove();
    var tagArray = new Array();
    $( '.tag-choosed-img>.system-tag>button', me ).each( function() {
      tagArray.push( $( this ).text() );
    } );
    $( '.select-tag', me ).selectpicker( 'val', tagArray );
  } );


  $( '.tag-choosed-img>.custom-tag', me ).on( 'click', 'button', function() {
    $( this ).remove();
    $( '.select-tag' ).selectpicker( multipleParam( {
      maxOptions: ( 5 - $( '.tag-choosed-img button', me ).length + $( '.tag-choosed-img>.system-tag>button' ).length )
    } ) );
  } );

  // 手动加标签
  $( '#inp-addtag-img', me ).keyup( function( e ) {
    e = e || event;
    var regx = /,/;
    var strRep = $.trim( $( this ).val() ).replace( /\s+/g, '' );
    var lastStr = strRep.substr( strRep.length - 1 );
    if ( regx.test( lastStr ) || e.keyCode == 13 ) {
      var tagLen = $( '.tag-choosed-img button', me ).length;
      var flag = true;
      $( '.tag-choosed-img button', me ).each( function() {
        if ( strRep == $( this ).text() ) {
          ShowTitleMessage.showWarning( '已存在相同的标签', showTime );
          flag = false;
          return false;
        }
      } );
      if ( tagLen < 5 ) {
        if ( $( '.tag-choosed-img>.custom-tag>button', me ).length == 4 && $( '.tag-choosed-img>.system-tag>button', me ).length == 0 ) {
          ShowTitleMessage.showWarning( '请至少选择一个系统标签', showTime );
          $( this ).val( '' );
          return;
        }
        if ( !flag ) {
          $( this ).val( '' );
          return;
        }
        var html = '';
        var array = strRep.split( ',' );
        for ( var i = 0; i < array.length; i++ ) {
          if ( array[ i ] != '' ) {
            html += '<button type="button" title="' + array[ i ] + '">' + array[ i ] + '</button>';
          }
        }
        if ( html != '' ) {
          $( '.tag-choosed-img>.custom-tag', me ).append( html );
          $( '.select-tag', me ).selectpicker( multipleParam( {
            maxOptions: ( 5 - tagLen - 1 + $( '.tag-choosed-img>.system-tag>button', me ).length )
          } ) );
        } else {
          ShowTitleMessage.showWarning( '空白标签无法添加', showTime );
        }
        $( this ).val( '' );
      } else {
        $( this ).val( '' );
        ShowTitleMessage.showWarning( '系统和自定义标签总共最多五个', showTime );
      }
    }
  } );

  me.on( 'click', '#example_image_qiniu .delete', function() {
    $( '#example_image_qiniu', me ).remove();
  } );
  // 重置上传图片参数
  $( '#fm_img_upload', me ).on( 'reset', function() {

    $( '.select-tag', this ).selectpicker( 'val', [] );
    $( '.video_classify', this ).selectpicker( 'val', '未选择' );
    $( '.selectpicker', this ).selectpicker( 'refresh' );
    $( '.system-tag, .custom-tag, .image_preview', this ).empty();
    $( '.image_upload', this ).text( '上传图片' );
    $( '.spa_fontcount>span', this ).text( 0 );
  } );

  that.on( 'reset', 'form', function() {
    var _this = this;
    setTimeout( function() {
      $( '.selectpicker', _this ).selectpicker( 'refresh' );
      $( '.bg_container', _this ).css( 'backgroundImage', '' );
    } );
  } );
  return returnParam;
} );
